<template>
  <div class="device-user-selector">
    <div class="user-list">
      <el-tag
        class="user-item"
        v-for="(item, index) in localUserList"
        @close="remove(index)"
        closable
        :key="index">
        {{item.realname}}
      </el-tag>
    </div>
    <div class="actions">
      <el-button type="danger" @click="onCheckedUserListChanged([])">清空</el-button>
      <el-button type="primary" @click="openUserChecker()">添加</el-button>
    </div>

    <check-people ref="checker" :checked-user-list="localUserList" :set-user-list="onCheckedUserListChanged"></check-people>
  </div>
</template>

<script>
import CheckPeople from '../../../../components/check/checkPeople'
export default {
  name: 'UserSelector',
  components: {
    CheckPeople
  },
  data () {
    return {
      userIds: [],
      localUserList: []
    }
  },
  props: {
    'userList': {
      required: true,
      type: Array
    }
  },
  methods: {
    onCheckedUserListChanged(userList) {
      this.localUserList = userList
      this.$emit('change', userList)
    },
    openUserChecker() {
      this.$refs.checker.init(this.userIds)
    },
    remove(index) {
      this.localUserList.splice(index, 1)
      this.$emit('change', this.localUserList)
    }
  },
  watch: {
    'userList' (newval) {
      if (newval !== undefined ) {
        this.localUserList = JSON.parse(JSON.stringify(newval))
      }
    }
  }
}
</script>

<style>
.device-user-selector {
  border: 1px solid #DDD;
  border-radius: 2px;
}

.device-user-selector > .user-list {
  min-height: 50px;
  margin: 10px;
}

.device-user-selector > .user-list > .user-item {
  margin: 5px;
}

.device-user-selector > .actions {
  display: flex;
  justify-content: flex-end;
  margin: 10px;
}
</style>
